package stark.app.function.ve;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.stark.trackview.lib.video.changespeed.ChangeSpeedBean;
import com.stark.trackview.lib.video.changespeed.ChangeSpeedSection;
import com.stark.trackview.lib.video.changespeed.IChangeSpeedTrackViewListener;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;
import com.stark.ve.core.SpeedMode;

import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpTimeSpeed;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.ActivitySegmentChangeSpeedBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

/**
 * Author：daizhongbin on 2025/4/15
 * Email：1027154338@qq.com
 * Desc:
 */
public class VideoSegmentChangeSpeedActivity extends BaseNoModelActivity<ActivitySegmentChangeSpeedBinding> implements IChangeSpeedTrackViewListener {

    private String mVideoPath;
    private ExoPlayer mExoPlayer;
    private SegmentChangeSpeedOperationFragment mOperationFragment;
    private boolean needResume = false;
    private Handler mHandler = new Handler();
    private float mCurPlaySpeed = 1.0f;
    private List<ChangeSpeedBean> mChangeSpeedBeanList;
    private Runnable taskGetPlayTime = new Runnable() {
        @Override
        public void run() {
            long curPlayTimeInMillis = mExoPlayer.getCurrentPosition();
            float speed = getSpeedByTime(curPlayTimeInMillis);
            if (speed > 0 && mCurPlaySpeed != speed) {
                mCurPlaySpeed = speed;
                mExoPlayer.setPlaybackParameters(new PlaybackParameters(speed));
            }
            mOperationFragment.moveTrackViewByTime(curPlayTimeInMillis);
            mHandler.postDelayed(this, 200);
        }
    };

    public static void start(Activity activity, String videoPath) {
        Intent intent = IntentUtil.getIntent(activity, VideoSegmentChangeSpeedActivity.class);
        intent.putExtra(Extra.PATH, videoPath);
        activity.startActivity(intent);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_segment_change_speed;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        mVideoPath = intent.getStringExtra(Extra.PATH);
        if (TextUtils.isEmpty(mVideoPath)) {
            finish();
            return;
        }
        // 添加操作Fragment
        addOperationFragment();

        View viewBack = findViewById(com.stark.ve.R.id.iv_back);
        if (viewBack != null) {
            viewBack.setOnClickListener(v -> {
                onBackPressed();
            });
        }
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("分段变速");
        View viewExport = findViewById(com.stark.ve.R.id.tv_export);
        if (viewExport != null) {
            viewExport.setOnClickListener(v -> {
                doExport();
            });
        }


        mExoPlayer = new ExoPlayer.Builder(this).build();
        mDataBinding.playerView.setPlayer(mExoPlayer);
        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(mVideoPath));
        mExoPlayer.setMediaItem(mediaItem);
        mExoPlayer.addListener(new Player.Listener() {
            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                if (isPlaying) {
                    mChangeSpeedBeanList = mOperationFragment.getAllChangeSpeedBeanList();
                    mHandler.post(taskGetPlayTime);
                } else {
                    mHandler.removeCallbacks(taskGetPlayTime);
                }
            }
        });
        mExoPlayer.prepare();
        mExoPlayer.play();
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needResume) {
            needResume = false;
            if (mExoPlayer != null) {
                mExoPlayer.play();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mExoPlayer != null && mExoPlayer.isPlaying()) {
            needResume = true;
            mExoPlayer.pause();
        }
    }

    @Override
    public void onTouchChangeSpeedSectionOrNot(@Nullable ChangeSpeedSection section) {
    }

    @Override
    public void onTouchDown() {
        mExoPlayer.pause();
    }

    @Override
    public void onMoveToTime(long timeInMillis) {
        mExoPlayer.seekTo(timeInMillis);
    }

    private void addOperationFragment() {
        SegmentChangeSpeedOperationFragment fragment = new SegmentChangeSpeedOperationFragment();
        mOperationFragment = fragment;
        fragment.setVideoPath(mVideoPath);
        fragment.setTrackViewListener(this);
        FragmentUtils.add(getSupportFragmentManager(), fragment, R.id.fl_bottom);
    }

    private float getSpeedByTime(long timeInMillis) {
        float speed = -1;
        if (mChangeSpeedBeanList == null || mChangeSpeedBeanList.size() == 1) {
            return speed;
        }
        for (ChangeSpeedBean bean : mChangeSpeedBeanList) {
            if (timeInMillis >= bean.startTime && timeInMillis < bean.endTime) {
                speed = bean.speed;
                break;
            }
        }
        return speed;
    }

    private List<EpTimeSpeed> getEpTimeSpeedList() {
        List<ChangeSpeedBean> beans = mOperationFragment.getAllChangeSpeedBeanList();
        List<EpTimeSpeed> speedList = new ArrayList<>();
        for (ChangeSpeedBean bean : beans) {
            EpTimeSpeed speed = new EpTimeSpeed();
            speed.startTime = bean.startTime / 1000;    //毫秒转换为秒
            speed.endTime = bean.endTime / 1000;
            speed.speed = bean.speed;
            speedList.add(speed);
        }
        return speedList;
    }

    private void doExport() {
        if (mExoPlayer == null) return;
        if (mExoPlayer.isPlaying()) {
            mExoPlayer.pause();
        }
        List<EpTimeSpeed> epTimeSpeedList = getEpTimeSpeedList();
        if (epTimeSpeedList == null || epTimeSpeedList.size() == 0) {
            ToastUtils.showShort("请先添加要变速的分段");
            return;
        }
        showDialog(getString(com.stark.ve.R.string.ve_handle_percent_format, 0 + "%"));
        EditorHolder.editor().segmentChangeSpeed(mVideoPath, epTimeSpeedList, SpeedMode.ALL, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                showDialog(getString(com.stark.ve.R.string.ve_exporting));
                exportOutFile(outFilePath);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                if (TextUtils.isEmpty(errMsg)) {
                    ToastUtils.showShort(com.stark.ve.R.string.ve_change_speed_fail_tip);
                } else {
                    ToastUtils.showShort(errMsg);
                }
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(com.stark.ve.R.string.ve_handle_percent_format, progress + "%"));
            }
        });

    }

    private void exportOutFile(String outFilePath) {
        RxUtil.create(new RxUtil.Callback<Uri>() {
            @Override
            public void doBackground(ObservableEmitter<Uri> emitter) {
                Uri uri = FileP2pUtil.copyPrivateVideoToPublic(VideoSegmentChangeSpeedActivity.this, outFilePath);
                FileUtils.delete(outFilePath);
                emitter.onNext(uri);
            }

            @Override
            public void accept(Uri uri) {
                dismissDialog();
                if (uri != null) {
                    ToastUtils.showShort(com.stark.ve.R.string.ve_export_success_tip);
                    //finish();
                } else {
                    ToastUtils.showShort(com.stark.ve.R.string.ve_export_failure);
                }
            }
        });
    }
}
